package com.example.workflow.service.impl;

import com.example.workflow.dto.OperatorHistoryListDto;
import com.example.workflow.dto.OperatorHistoryListDto.OperatorHistoryItem;
import com.example.workflow.dto.OperatorStatsDto;
import com.example.workflow.mapper.OrderLogMapper;
import com.example.workflow.service.OperatorStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 操作人员工单统计服务实现类
 */
@Service
@Slf4j
public class OperatorStatsServiceImpl implements OperatorStatsService {
    @Autowired
    private OrderLogMapper orderLogMapper;
    
    @Override
    public OperatorStatsDto getOperatorStats(Integer operatorId) {
        log.info("获取操作人员工单统计，操作人员ID: {}", operatorId);
        
        // 创建返回对象
        OperatorStatsDto stats = new OperatorStatsDto();
        
        // 1. 获取操作人员的工单处理数量
        Map<String, Object> counts = orderLogMapper.countOperateOrders(operatorId);
        // 设置一级操作的工单数量 - 表示操作人员作为operate_first处理的工单数
        stats.setFirstOrderCount(((Number)counts.get("first_order_count")).intValue());
        // 设置二级操作的工单数量 - 表示操作人员作为operate_second处理的工单数
        stats.setSecondOrderCount(((Number)counts.get("second_order_count")).intValue());
        
        // 2. 获取操作人员所属部门
        String department = orderLogMapper.getOperatorDepartment(operatorId);
        if (department != null && !department.isEmpty()) {
            log.info("操作人员所属部门: {}", department);
            
            // 3. 获取该部门派发的工单数量
            Integer departmentDispatchedCount = orderLogMapper.countDepartmentDispatchedOrders(department);
            stats.setDepartmentDispatchedCount(departmentDispatchedCount);
            log.info("部门派发工单数量: {}", departmentDispatchedCount);
        } else {
            log.warn("未找到操作人员部门信息");
            stats.setDepartmentDispatchedCount(0);
        }
        
        return stats;
    }
    
    /**
     * 获取操作人员处理过的历史工单列表
     * URL: /operator/list
     *
     * @param operatorId 操作人员ID
     * @return 历史工单列表
     */
    @Override
    public OperatorHistoryListDto getOperatorHistoryList(Integer operatorId) {
        log.info("获取操作人员历史工单列表，操作人员ID: {}", operatorId);
        
        // 查询历史工单列表
        List<OperatorHistoryItem> historyItems = orderLogMapper.getOperatorHistoryList(operatorId);
        log.info("查询到操作人员历史工单 {} 条", historyItems.size());
        
        // 封装返回结果
        OperatorHistoryListDto result = new OperatorHistoryListDto();
        result.setItems(historyItems);
        result.setTotalCount(historyItems.size());
        
        return result;
    }
} 